<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="汇报类型" prop="reportType">
        <el-radio-group v-model="formData.reportType" @change="handleReportTypeChange">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.OA_REPORT_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 参会人员 - 使用 UserSelectDialog 多选模式 -->
      <el-form-item label="接收人" prop="recipient">
        <div>
          <!-- 显示已选择的参会人员 -->
          <div v-if="selectedParticipants.length > 0" class="mb-2">
            <el-tag
              v-for="user in selectedParticipants"
              :key="user.id"
              closable
              @close="removeParticipant(user.id)"
              type="primary"
              class="mr-2 mb-2"
            >
              {{ user.nickname }}({{ user.username }})
            </el-tag>
          </div>

          <!-- 选择按钮 -->
          <el-button @click="openParticipantDialog" type="primary" plain>
            <Icon icon="ep:plus" />
            选择接收人{{ selectedParticipants.length > 0 ? `(${selectedParticipants.length})` : '' }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="汇报日期" prop="reportPeriod">
        <el-col :span="6">
          <el-date-picker
            v-model="formData.reportPeriod"
            :type="datePickerType"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            placeholder="选择日期"
            :shortcuts="shortcuts"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="本期工作内容" prop="currentWork">
        <el-input v-model="formData.currentWork" type="textarea"  :rows = "4" placeholder="请输入本期工作内容" />
      </el-form-item>
      <el-form-item label="下期计划计划" prop="nextPlan">
        <el-input v-model="formData.nextPlan" type="textarea"  :rows = "4" placeholder="请输入明日计划" />
      </el-form-item>
      <el-form-item label="其它事项" prop="otherMatters">
        <el-input v-model="formData.otherMatters" type="textarea"  :rows = "4" placeholder="请输入其它事项" />
      </el-form-item>
<!--      <el-form-item label="附件URL列表" prop="attachmentUrls">-->
<!--        <el-button type="primary">Primary</el-button>-->
<!--      </el-form-item>-->

      <!-- 相关附件 -->
      <el-col :span="24">
        <el-form-item label="相关附件" >
          <OaFileManager :folderDisabled="true" :initial-file-ids="formData.files" @fileSelectSuccess="fileSelectScccess"  />
        </el-form-item>
      </el-col>

    </el-form>
    <template #footer>
      <el-button @click="submitForm(0)" type="primary" :disabled="formLoading">仅保存</el-button>
      <el-button @click="submitForm(1)" type="primary" :disabled="formLoading">保存并发送</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <!-- 参会人员选择对话框 -->
  <UserSelectDialog
    v-model="participantDialogVisible"
    :multiple="true"
    :selected-ids="selectedParticipantIds"
    title="选择接收人"
    @confirm="handleParticipantConfirm"
  />
</template>
<script setup lang="ts">
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { WorkReportApi, WorkReportVO } from '@/api/oa/workreport'
import * as UserApi from '@/api/system/user'
import UserSelectDialog from '@/views/system/user/UserSelectDialog.vue'
import { formatDate } from '@/utils/formatTime'

/** 工作汇报 表单 */
defineOptions({ name: 'WorkReportForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  reportType: undefined,
  recipient: undefined,
  reportPeriod: undefined,
  reportDate: undefined,
  currentWork: undefined,
  nextPlan: undefined,
  otherMatters: undefined,
  attachmentUrls: undefined,
  reportStatus: undefined,
  sendTime: undefined
})
const formRules = reactive({
  reportType: [{ required: true, message: '汇报类型不能为空', trigger: 'blur' }],
  recipient: [{ required: true, message: '接收人不能为空', trigger: 'blur' }],
  reportPeriod: [{ required: true, message: '汇报周期不能为空', trigger: 'blur' }],
  currentWork: [{ required: true, message: '本期工作内容不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const fileSelectScccess = (fileIds: string[]) => {
  formData.value.files = fileIds.join(',')
}

// 日期选择器类型，根据汇报类型动态设置
const datePickerType = computed(() => {
  // 假设字典值：1-日报，2-周报，3-月报
  if (formData.value.reportType === '1') {
    return 'date' // 日报使用单日期选择器
  } else {
    return 'daterange' // 周报和月报使用日期范围选择器
  }
})

const shortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    },
  },
  {
    text: '最近一月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    },
  },
]

// 参会人员相关
const participantDialogVisible = ref(false)
const selectedParticipants = ref<UserApi.UserVO[]>([])
const selectedParticipantIds = computed(() => selectedParticipants.value.map(user => String(user.id)))

/**
 * 处理汇报类型变化
 * @param value 汇报类型值
 */
const handleReportTypeChange = (value: string) => {
  // 根据汇报类型设置默认日期
  const today = new Date()

  if (value === '1') {
    // 日报：默认选择当天
    formData.value.reportPeriod = formatDate(today, 'YYYY-MM-DD')
  } else if (value === '2') {
    // 周报：默认选择最近一周
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
    formData.value.reportPeriod = [
      formatDate(start, 'YYYY-MM-DD'),
      formatDate(end, 'YYYY-MM-DD')
    ]
  } else if (value === '3') {
    // 月报：默认选择最近一月
    const end = new Date()
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
    formData.value.reportPeriod = [
      formatDate(start, 'YYYY-MM-DD'),
      formatDate(end, 'YYYY-MM-DD')
    ]
  }
}

/**
 * 格式化汇报日期为字符串
 * @param reportPeriod 汇报日期
 * @param reportType 汇报类型
 * @returns 格式化后的日期字符串
 */
const formatReportDate = (reportPeriod: any, reportType: string): string => {
  if (!reportPeriod) return ''

  if (reportType === '1') {
    // 日报：单个日期
    return typeof reportPeriod === 'string' ? reportPeriod : formatDate(reportPeriod, 'YYYY-MM-DD')
  } else {
    // 周报和月报：日期范围
    if (Array.isArray(reportPeriod) && reportPeriod.length === 2) {
      const startDate = typeof reportPeriod[0] === 'string' ? reportPeriod[0] : formatDate(reportPeriod[0], 'YYYY-MM-DD')
      const endDate = typeof reportPeriod[1] === 'string' ? reportPeriod[1] : formatDate(reportPeriod[1], 'YYYY-MM-DD')
      return `${startDate} 至 ${endDate}`
    }
    return ''
  }
}

/**
 * 解析汇报日期字符串
 * @param dateStr 日期字符串
 * @param reportType 汇报类型
 * @returns 解析后的日期对象
 */
const parseReportDate = (dateStr: string, reportType: string): any => {
  if (!dateStr) return null

  if (reportType === '1') {
    // 日报：单个日期
    console.log('日报日期:', dateStr)
    return dateStr
  } else {
    // 周报和月报：日期范围
    if (dateStr.includes(' 至 ')) {
      const dates = dateStr.split(' 至 ')
      if (dates.length === 2) {
        return [dates[0].trim(), dates[1].trim()]
      }
    }
    return null
  }
}

/** 根据参会人员字符串加载用户信息 */
const loadSelectedParticipants = async (participantsStr: string) => {
  try {
    // 假设参会人员字段存储的是用户ID，用逗号分隔
    // 如果存储格式不同，需要根据实际情况调整解析逻辑
    const userIds = participantsStr.split(',').map(id => id.trim()).filter(id => id)

    if (userIds.length > 0) {
      const users = await Promise.all(
        userIds.map(async (id) => {
          try {
            return await UserApi.getUser(Number(id))
          } catch {
            return null
          }
        })
      )
      selectedParticipants.value = users.filter(user => user !== null) as UserApi.UserVO[]
    }
  } catch (error) {
    console.error('加载参会人员失败:', error)
  }
}

/** 打开参会人员选择对话框 */
const openParticipantDialog = () => {
  participantDialogVisible.value = true
}

/** 处理参会人员选择确认 */
const handleParticipantConfirm = (users: UserApi.UserVO[], ids: string[]) => {
  selectedParticipants.value = users
  // 更新表单数据 - 这里可以根据实际需求存储用户ID或其他格式
  formData.value.recipient = ids.join(',')

  console.log('选择的参会人员:', users)
  console.log('参会人员IDs:', ids)
}

/** 移除参会人员 */
const removeParticipant = (userId: number) => {
  const index = selectedParticipants.value.findIndex(user => user.id === userId)
  if (index > -1) {
    selectedParticipants.value.splice(index, 1)
    // 更新表单数据
    const remainingIds = selectedParticipants.value.map(user => String(user.id))
    formData.value.recipient = remainingIds.join(',')
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const record = await WorkReportApi.getWorkReport(id)
      formData.value = {
        ...record,
        // 解析汇报日期
        reportPeriod: parseReportDate(record.reportPeriod, record.reportType.toString()),
        reportType: record.reportType.toString(),
      }
      // 如果有参会人员数据，需要解析并设置选中的参会人员
      if (record.recipient) {
        await loadSelectedParticipants(record.recipient)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (status: number) => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = {
      ...formData.value,
      reportStatus: status,
      // 格式化汇报日期为字符串
      reportPeriod: formatReportDate(formData.value.reportPeriod, formData.value.reportType)
    } as unknown as WorkReportVO

    if (formType.value === 'create') {
      await WorkReportApi.createWorkReport(data)
      message.success(t('common.createSuccess'))
    } else {
      await WorkReportApi.updateWorkReport(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    reportType: undefined,
    recipient: undefined,
    reportPeriod: undefined,
    reportDate: undefined,
    currentWork: undefined,
    nextPlan: undefined,
    otherMatters: undefined,
    attachmentUrls: undefined,
    reportStatus: undefined,
    sendTime: undefined
  }
  selectedParticipants.value = []
  formRef.value?.resetFields()
}
</script>
